/**
 * Copyright (c) 2013-Now http://vben.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
 */
import { Ref, reactive } from "vue";
import { isEmpty } from "$/utils/is";
import { listToTree } from "$/utils/helper/treeHelper";
// 请求字典的方法
const dictDataTreeData = (arg: any) => {
  return new Promise<any>((resolve, reject) => {
    return setTimeout(() => {
      return resolve({});
    }, 3000);
  });
};

export function useDict() {
  const dictListMap = reactive<any>({});

  async function initDict(dictTypes: string[] | Set<string> = []) {
    if (!dictTypes) return;
    for (const dictType of dictTypes) {
      if (!dictListMap[dictType]) {
        dictListMap[dictType] = await dictDataTreeData({ dictType: dictType });
      }
    }
  }

  function getDictList(dictType: string): Recordable[] {
    return dictListMap[dictType] || [];
  }

  function getDictLabel(
    dictType: string,
    value?: string,
    defaultValue = t("未知")
  ): string {
    const result: string[] = [];
    for (const item of getDictList(dictType)) {
      if (item && ("," + value + ",").includes("," + item.value + ",")) {
        result.push(item.name);
      }
    }
    return result.length > 0 ? result.join(",") : defaultValue;
  }

  async function initSelectOptions(optionsRef: Ref, dictType?: string) {
    if (isEmpty(dictType)) return;
    await initDict([dictType]);
    const vbenDictList = getDictList(dictType);
    optionsRef.value = vbenDictList.map((item) => ({
      label: item.name,
      value: item.value,
      key: item.id,
    }));
  }

  async function initSelectTreeData(
    treeData: Ref,
    dictType: string,
    isListToTree: boolean
  ) {
    if (isEmpty(dictType)) return;
    await initDict([dictType]);
    const vbenDictList = getDictList(dictType);
    if (isListToTree) {
      treeData.value = listToTree(vbenDictList);
    } else {
      treeData.value = vbenDictList;
    }
  }

  return {
    initDict,
    getDictList,
    getDictLabel,
    initSelectOptions,
    initSelectTreeData,
  };
}
